package com.project;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackageClasses = MyBatisConfig.class)
@MapperScan("com.project.mapper") // 设置mapper文件所在的包
public class MyBatisConfig {

    /**
     * 设置数据源
     * @return 数据源对象
     */
    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        //设置驱动类
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //设置URL
        dataSource.setUrl("jdbc:mysql://localhost:6789/mybatisDB?characterEncoding=utf-8&amp;allowMultiQueries=true");
        //设置mysql登陆用户名
        dataSource.setUsername("root");
        //设置mysql的登陆密码
        dataSource.setPassword("lovo");
        //设置最大连接数
        dataSource.setMaxActive(100);
        //设置最小连接数
        dataSource.setMinIdle(20);
        //设置等待时间
        dataSource.setMaxWait(1000);
        return dataSource;
    }

    /**
     * 得到Mapper实现类对象
     * @return SqlSessionFactoryBean对象
     */
    @Bean
    public SqlSessionFactoryBean getFactoryBean(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置数据源
        factoryBean.setDataSource(this.getDataSource());
        //读取mybatis的主配置文件
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));

        return factoryBean;
    }

    /**
     * 得到事务管理器
     * @return 事务管理器
     */
    @Bean
    public TransactionManager getTransactionManager(){
        DataSourceTransactionManager trans = new DataSourceTransactionManager(this.getDataSource());
        return trans;
    }
}
